//
//  BankCardViewController.m
//  YDD
//
//  Created by 欧洪飞 on 2017/8/22.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "BankCardViewController.h"

#import "BankCardCell.h"
#import "AddCardViewController.h"
@interface BankCardViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *array1;//数据源
    UIImageView *imageView;
    UILabel *labTit;
    UITableViewCellEditingStyle editStyle;//
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *noView;


@end

@implementation BankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    //[self showNav:@"选择银行卡"];
    array1 = [NSMutableArray array];
    [self loadNav];
//    [self loadData];
    [self loadUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"选择银行卡";
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn1 setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn1 addTarget:self action:@selector(click1) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn1];
    [btn1 makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.left.equalTo(view.left).offset(0);
        make.width.height.equalTo(40);
    }];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setTitle:@"编辑" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(click2) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn2];
    [btn2 makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.right.equalTo(view.right);
        make.width.equalTo(40);
        make.height.equalTo(38);
    }];
}

- (void)click1{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)click2{
    editStyle = UITableViewCellEditingStyleDelete;
    if (_tableView.isEditing) {
        [_tableView setEditing:NO animated:YES];
    }else{
        [_tableView setEditing:YES animated:YES];
    }
}


- (void)loadUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50) style:UITableViewStylePlain];
    _tableView.dataSource = self;//44*10+60
    _tableView.delegate = self;
    _tableView.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = 65.0;
    [self.view addSubview:_tableView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, ScreenHeight-50, ScreenWidth, 50.0);
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitle:@" 添加银行卡" forState:UIControlStateNormal];
    [btn setTitleColor:COLOR_RGB(65, 132, 255, 1) forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"矩形-21-拷贝"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickAddCard) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"available"]];
    imageView.hidden = YES;
    [self.view addSubview:imageView];
    [imageView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.centerY.equalTo(self.view.centerY);
    }];
    
    labTit = [[UILabel alloc] init];
    labTit.text = @"暂无银行卡...";
    labTit.hidden = YES;
    labTit.font = [UIFont systemFontOfSize:15.0];
    labTit.textColor = [UIColor lightGrayColor];
    [self.view addSubview:labTit];
    [labTit makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(imageView.bottom).offset(8);
    }];
    
}

- (void)clickAddCard{
    AddCardViewController *addcard = [[AddCardViewController alloc] init];
    [self.navigationController pushViewController:addcard animated:YES];
}

#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array1.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    BankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"BankCardCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = array1[indexPath.row];
    NSString *is_default = [dic objectForKey:@"is_default"];
    if ([is_default integerValue] == 2) {//是否设置成默认银行卡  2为是，3为否
        cell.images.image = [UIImage imageNamed:@"勾"];
    }else{
        cell.images.image = [UIImage imageNamed:@""];
    }
    
    cell.labTit.text = [dic objectForKey:@"bankname"];
    NSString *banknumber = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"banknumber"] integerValue]];
    NSInteger count = banknumber.length;
    NSInteger a = count-4;
    NSString *num = [banknumber substringFromIndex:a];
    NSLog(@"num:%@",num);
    //
    cell.labDet.text = [NSString stringWithFormat:@"尾号 %@ 储蓄卡",num];
    
    NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[dic objectForKey:@"banklogo"]];
    [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"工行"]];
    
    
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//提供编辑的样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return editStyle;
}

//提交编辑状态
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = array1[indexPath.row];
    NSString *bankid = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"id"] integerValue]];
    NSLog(@"dic:%@",dic);
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [array1 removeObject:dic];
        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self loadData3:bankid];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //设置默认银行卡
    [self loadData2];
    //删除
    //[self loadData3];
    
}

//展示银行卡
- (void)loadData{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/banklist",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"展示银行卡res:%@",responseObject);
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([state integerValue] == 200) {
            array1 = [responseObject objectForKey:@"content"];
            
        }else if ([state integerValue] == 205){//没有银行卡
            _tableView.hidden = YES;
            imageView.hidden = NO;
            labTit.hidden = NO;
        }
        
        [_tableView reloadData];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}
//设置默认银行卡
- (void)loadData2{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setObject:@"4" forKey:@"bankid"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/settingbank",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"设置默认银行卡res:%@",responseObject);
        NSString *status = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([status integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}
//删除银行卡
- (void)loadData3:(NSString *)bankid{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setObject:bankid forKey:@"bankid"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/deleBank",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"删除银行卡res:%@",responseObject);
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        NSString *msg = [responseObject objectForKey:@"msg"];
        if ([state integerValue] == 200) {
            
            [self loadData];
        }
        [LICGToast showWithText:msg];
        [_tableView reloadData];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
